package cn.broadin.app.hotel.component;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.broadin.app.hotel.HomeActivity;
import cn.broadin.app.hotel.R;
import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUtils;

/**
 * 视频直播窗口组件
 */
public class LiveView extends BaseView<LiveViewData> implements SurfaceHolder.Callback{

    private SurfaceView mSurfaceView;

    private ImageView mLoadImageView;

    private Animation mRotateAnimation;

    private SurfaceHolder mSurfaceHolder;

    private MediaPlayer mMediaPlayer;

    // 播放界面宽度
    private int mVideoWidth;
    // 播放界面高度
    private int mVideoHeight;

    public LiveView(Context context, LiveViewData data) {
        super(context, data);
    }

    @Override
    protected View onCreateView(RelativeLayout rootView){
        FrameLayout frameLayout = new FrameLayout(mContext);

        // 播放窗口
        this.mSurfaceView = new SurfaceView(mContext);
        FrameLayout.LayoutParams surfaceViewLayoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        frameLayout.addView(mSurfaceView, surfaceViewLayoutParams);
        // Loading框
        int width = (int) XUtils.getDimension(mContext, R.dimen.px120);
        int height = (int) XUtils.getDimension(mContext, R.dimen.px120);
        FrameLayout.LayoutParams loadImageViewLayoutParams = new FrameLayout.LayoutParams(width, height);
        loadImageViewLayoutParams.gravity = Gravity.CENTER;
        this.mLoadImageView = new ImageView(mContext);
        this.mLoadImageView.setImageResource(R.drawable.icon_loading);
        frameLayout.addView(mLoadImageView, loadImageViewLayoutParams);
        // 初始化动画效果
        this.mRotateAnimation = AnimationUtils.loadAnimation(mContext, R.anim.loading_rotate);
        this.mLoadImageView.startAnimation(mRotateAnimation);

        this.mSurfaceHolder = mSurfaceView.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        return frameLayout;
    }

    @Override
    public void onClick(View v) {
        try{
            String pkg = null;
            String cls = null;
            if(!TextUtils.isEmpty(mData.params)){
                JSONObject jsonObject = JSON.parseObject(mData.params);
                pkg = jsonObject.getString("pkg");
                cls = jsonObject.getString("pkg");
            }
            pkg = getValue(pkg, "com.hotel.player");
            cls = getValue(cls, "com.hotel.player.PlayerActivity");
            openThirdApp(getContext(), pkg, cls);
        } catch (Exception e){
            e.printStackTrace();
            XToast.makeText(mContext, "应用启动失败！").show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        initMediaPlayer();
    }

    @Override
    public void onPause() {
        super.onPause();

        releaseMediaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        releaseMediaPlayer();
    }

    public static LiveView newInstance(Context context, JSONObject jsonObject){
        LiveViewData data = JSON.toJavaObject(jsonObject, LiveViewData.class);
        return newInstance(context, data);
    }

    public static LiveView newInstance(Context context, LiveViewData data){
        return new LiveView(context, data);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        XLog.d("surfaceCreated");
        initMediaPlayer();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        XLog.d("surfaceDestroyed");
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        super.onDestroy();
    }

    /**
     * 创建直播窗口播放对象
     */
    private void initMediaPlayer(){
        String url = ((HomeActivity) mContext).getIndexVideoPath();
        XLog.i("video url: " + url);
        if(mMediaPlayer != null){
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        mMediaPlayer = new MediaPlayer();
        try{
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.setDisplay(mSurfaceHolder);
            mMediaPlayer.prepareAsync();

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 设置错误异常监听器
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    XLog.e("play video error!!! what: " + what + ", extra: " + extra);
                    XToast.makeText(mContext, "视频播放失败！").show();
                    return true;
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 视频播放完成
                    XLog.d("onCompletion");
                    initMediaPlayer();
//					mMediaPlayer.start();
                }
            });
            // 视频播放预处理
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mVideoWidth = mMediaPlayer.getVideoWidth();
                    mVideoHeight = mMediaPlayer.getVideoHeight();
                    XLog.d("onPrepared called, width: " + mVideoWidth + ", height: " + mVideoHeight);
                    if (mVideoWidth != 0 && mVideoHeight != 0) {

                        if(mLoadImageView != null) {
                            mLoadImageView.clearAnimation();
                            mLoadImageView.setVisibility(View.INVISIBLE);
                        }
                        /* 设置视频的宽度和高度 */
                        mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
                        /* 开始播放 */
                        mMediaPlayer.start();
                    }
                }
            });
            mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    XLog.d("onBufferingUpdate, percent: " + percent);
                }
            });
            mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mp, int what, int extra) {
                    if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START){

                        mLoadImageView.startAnimation(mRotateAnimation);
                        mLoadImageView.setVisibility(View.VISIBLE);

                    } else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END){

                        mLoadImageView.clearAnimation();
                        mLoadImageView.setVisibility(View.INVISIBLE);
                    }
                    XLog.d("setOnInfoListener, what: " + what + ", extra " + extra);
                    return false;
                }
            });
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            // mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
